import os
import uuid
import random
import time
import jieba

from aip import AipSpeech

file_path = os.path.dirname('..')

APP_ID = "11307048"
API_KEY = "srGybYQvvoNN7BNHrO5Tu9TY"
SK = "TUpN5hKOoKv5zzA7N0w2N0y38KzlKo6W"

client = AipSpeech(APP_ID, API_KEY, SK)


# 语音合成
def text_to_audio(text):
    file_name = str("%s/" % random.randint(1, 20) + str(uuid.uuid1())) + ".mp3"
    file_content = client.synthesis(text, "zh", 1, {
        "per": 4
    })

    with open(os.path.join(file_path, "static", "audio", file_name), "wb") as f:
        f.write(file_content)

    return file_name


# 语音识别
def audio_to_text(file_name):
    cmd = "ffmpeg -y  -i %s  -acodec pcm_s16le -f s16le -ac 1 -ar 16000 %s.pcm" % (file_name, file_name)
    os.system(cmd)

    with open(file_name + ".pcm", "rb") as f:
        res_text = client.asr(f.read(), "pcm", 16000)

    return res_text


def clear():
    os.system('find static/* -name "*[mp3|wav|pcm]" -exec rm -rf {} \;')


if __name__ == "__main__":
    # clear()

    # text = '工资单'
    # text_to_audio(text/6)/6
    # fn = 'synchronize_code_success_msg'

    print(text_to_audio('正在同步测试代码'))
